<?php

header('content-type:text/html; charset=UTF-8');

	// 判断用户是否已登陆，未登录提示请先登陆
	if(empty($_SESSION['admin'])){

	  echo '<script>alert("请先登录");location.href="login.php"</script>';die;

	}

	// 判断是否有提交
	if(!empty($_POST)){

		//调用图片上传函数
		$savePath = '';
		if(!empty($_FILES['file']['name'][0])){
			$filelist = array();
			//数组重组
			foreach ($_FILES['file']['name'] as $key => $v) {
				$filelist[$key]['name'] = $v;
				$filelist[$key]['type'] = $_FILES['file']['type'][$key];
				$filelist[$key]['tmp_name'] = $_FILES['file']['tmp_name'][$key];
				$filelist[$key]['error'] = $_FILES['file']['error'][$key];
				$filelist[$key]['size'] = $_FILES['file']['size'][$key];
			}
			foreach ($filelist as $value) {
				$savePath[] = uploads($value);
			}
			
		}
		

		// 获取POST数据
		$title = $_POST['title'];//标题
		$cate_id = $_POST['type'];//类型
		// $file = $_POST['file'];//图片
		$content = $_POST['content'];//内容
		$author = $_POST['author'];//作者
		$send_user = $_SESSION['admin']['username'];//发布人
		// $add_time = time();//发布日期
		$url = empty($savePath[0])?'':$savePath[0];//图片上传路径
		$type = $_POST['type'];//图片类型

		//编写插入的sql语句
		$sql = "insert into `news`(`title`,`cate_id`,`content`,`author`,`send_user`,`url`,`type`)values('$title','$cate_id','$content','$author','$send_user','$url','$type')";

		// 执行sql语句
		mysqli_query($link,$sql);
		// 获取刚刚执行的添加语句受影响的行数（就是你插入的数据的记录总数）
		$_rows = mysqli_affected_rows($link);
		if($_rows>0){

			//生成静态页操作开始
			//获取刚添加的新闻内页id
			$id = mysqli_insert_id($link);
			//获取动态页面的数据
			$conStr = file_get_contents("http://localhost/cms/index.php?c=news&a=detail&id=$id");

			//把动态页面的数据写到指定的文件夹下生成静态页面
			file_put_contents("./html/$id.html",$conStr);die;
			//生成静态页操作结束
			
				echo '<script>alert("数据添加成功");location.href="index.php?c=news&a=list&admin=1";</script>';die;
	              
		}else{
			echo '<script>alert("数据添加失败");history.go(-1);</script>';die;
		}
	}

$id = empty($_GET['id'])?0:$_GET['id'];
	//查询顶级分类
	$sql = "select * from `cate` where pid=$id";
	$result = mysqli_query($link,$sql);
	while($arr = mysqli_fetch_assoc($result)){
		$cate[] = $arr;
	}

//判断是否是ajax发送的请求
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])){

	echo json_encode($cate);die;
}

// 加载后台首页视图
include('protected/view/admin/layout.html');